<?php
/**
 * 用户登录登出控制
 * User: t.young
 * Date: 2017/12/14
 * Time: 10:02
 */

namespace backend\controllers;


use backend\component\BackendBaseController;
use backend\component\ResultFormat;
use backend\models\LoginForm;
use common\component\XxteaD;


class AccountController extends BackendBaseController
{
    public $layout = "/login";

    //public $enableCsrfValidation = false;

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'common\component\CaptchaI',
                'maxLength' => 4,
                'minLength' => 4,
                'height'=> 40,
                'width'=> 80,
                'imageLibrary'=> 'gd',
                'foreColor' => 0x2eaeff,
            ]
        ];
    }

    /**
     * 加载登录视图
     */
    public function actionLogin() {
        return $this->render("login");
    }

    /**
     * 执行登录
     */
    public function actionDoLogin() {

        $model = new LoginForm();
        $model->setScenario("login");

        $postData = \Yii::$app->request->post();
        //解密密码
        $csrfBackendToken = $postData['_csrf-backend'];
        $encryptPassword = trim($postData['LoginForm']['password']);

        $postData['LoginForm']['password'] = XxteaD::decrypt($encryptPassword,$csrfBackendToken);
        //如果赋值&&登录成功
        if ($model->load($postData) && $model->login()) {
            return ResultFormat::success("登录成功");
        }
        return ResultFormat::error("登录失败，原因：".$model->getErrorsToString());
    }

    public function actionLogout() {
        \Yii::$app->user->logout();
        return $this->goHome();
    }
}
